
/** 初始化设置等都在 summary-req.js 中**/
//var canHtmlSign = false;
var isLoadFromCache = false;
cmp.ready(function(){

	if(forwardError != null){
		_alert(forwardError, _goBack);
        return;
	}
    _initBackEvent();
	cmp.dialog.loading();

    cmp.i18n.init(_collPath + "/i18n/", "Collaboration", function(){

        //国际化title标签
        _$("title").innerText = cmp.i18n("collaboration.affairs.details");

        //触发h1加载缓慢的触发器         --搞不明白为什要这么写，搞不懂，就抽一下变量
        var $showTitle = _$("#showTitle");
        $showTitle.style.bottom = '0px';
        $showTitle.style.display = 'block';

        //初始化数据检测
        if(!paramCheck){
            _alert(cmp.i18n("collaboration.exception.paramsException"), _goBack);
            return;
        }

      //加载数据
        FastUtil.call("fast_summary", {
            "success" : function(result, isCache){
				
                var toRend = true;
                if(!isCache){
                    toRend = _handReqData(result);
                }
				if(isCache){
					isLoadFromCache = true;
				}
                if(toRend){
                    _renderMainPage();
                }
            },
            "error" : function(error, isCache){
                pageX.isInitError = true;
                var cmpHandled = cmp.errorHandler(error);
                if(cmpHandled){

                 }else {
                     _alert(cmp.i18n("collaboration.exception.loadDataException")+error, _goBack);
                 }
            }
        })
    });

    $(window).bind('unload',function(){
        cmp.storage.save("summary_page_pause", "true", true);
    });
});


/**
 * 处理请求返回的数据
 */
function _handReqData(result){


    /** 前Affair状态校验 */
    if(result["error_msg"] && result["error_msg"]!="") {
        _alert(result["error_msg"], _goBack, cmp.i18n("collaboration.page.dialog.note"));
        cmp.dialog.loading(false);
        return false;
    }else{
        //注册summaryBO
        window.summaryBO = result["data"]||result;

        //数据补填
		summaryBO.openFrom = pageX.winParams["openFrom"];
        summaryBO.draftComment = summaryBO.draftComment || {};
        summaryBO.pageConfig = summaryBO.pageConfig || {};
		canHtmlSign = summaryBO.pageConfig.HtmlSign;

        var nodeActions = summaryBO.pageConfig.nodeActions || [];
        var commonActions = summaryBO.pageConfig.commonActions || [];
        var advanceActions = summaryBO.pageConfig.advanceActions || [];
        //权限合并
        nodeActions = nodeActions.concat(commonActions, advanceActions);
		//处理界面的操作合并到详情
		commonActions = commonActions.concat(advanceActions);
        summaryBO.pageConfig.nodeActions = nodeActions;
        summaryBO.pageConfig.commonActions = commonActions;
        summaryBO.pageConfig.advanceActions = advanceActions;

        summaryBO.backIndex = pageX.winParams.backIndex || 0;

        //系统时间和本地时间的差异
        summaryBO.server2LocalTime = summaryBO["SystemCurrentTimeMillis"] - new Date().getTime();

        //意见草稿
        if(summaryBO.draftComment["attachments"]){
            //附件转换成json格式
            summaryBO.draftComment["attachments"] = cmp.parseJSON(summaryBO.draftComment["attachments"]);
        }
        summaryBO.workflowCheckParam = summaryBO.workflowCheckParam || {};
		if(summaryBO.pageConfig.formDefaultShow == 0){//默认显示正文
			_showConent1();
		}
        return true;
    }
}

/**
 * 首屏数据加载完成后，渲染主入口
 */
function _renderMainPage(){

    LazyUtil.addLazyStack({
        "code" : "lazy_cmp",
        "css" : [
                _cmpPath + "/css/cmp-selectOrg.css" + $verstion,
                _cmpPath + "/css/cmp-picker.css" + $verstion,
                _cmpPath + "/css/cmp-search.css" + $verstion,
                _cmpPath + "/css/cmp-accDoc.css" + $verstion,
                _cmpPath + "/css/cmp-audio.css" + $verstion
                 ],
        "js" : [
                _cmpPath + "/js/cmp-flowV5.js" + $verstion,
                _cmpPath + "/js/cmp-accDoc.js" + $verstion,
                _cmpPath + "/js/cmp-push.js" + $verstion,
                _cmpPath + "/js/cmp-audio.js" + $verstion,
                _cmpPath + "/js/cmp-server.js" + $verstion,
                _cmpPath + "/js/cmp-lbs.js" + $verstion,
                _cmpPath + "/js/cmp-selectOrg.js" + $verstion,
                _cmpPath + "/js/cmp-picker.js" + $verstion,
                _cmpPath + "/js/cmp-dtPicker.js" + $verstion,
                _cmpPath + "/js/cmp-search.js" + $verstion,
                _cmpPath + "/js/cmp-popPicker.js" + $verstion,
                _cmpPath + "/js/cmp-camera.js" + $verstion,
                _cmpPath + "/js/cmp-webviewListener.js" + $verstion,
                _cmpPath + "/js/cmp-v5.js" + $verstion,
                _cmpPath + "/js/cmp-barcode.js" + $verstion
                ]
    });
	
	LazyUtil.addLazyStack({
        "code" : "form_edoc",
        "css" : [],
        "js" : [
                			
				_cmpPath + "/js/cmp-flowV5.js" + $verstion,
				//_cmpPath + "/js/cmp-listView.js" + $verstion,
				//_cmpPath + "/js/cmp-zoom.js" + $verstion,
				_cmpPath + "/js/cmp-accDoc.js" + $verstion,
				_cmpPath + "/js/cmp-app.js" + $verstion,
				_cmpPath + "/js/cmp-lbs.js" + $verstion,
				_cmpPath + "/js/cmp-imgCache.js" + $verstion,
				_cmpPath + "/js/cmp-selectOrg.js" + $verstion,
				_cmpPath + "/js/cmp-att.js" + $verstion,
				_cmpPath + "/js/cmp-picker.js" + $verstion,
				_cmpPath + "/js/cmp-dtPicker.js" + $verstion,
				_cmpPath + "/js/cmp-push.js" + $verstion,
				_cmpPath + "/js/cmp-audio.js" + $verstion,
				_cmpPath + "/js/cmp-server.js" + $verstion,
				_cmpPath + "/js/cmp-headerFixed.js" + $verstion,
				_cmpPath + "/js/cmp-description.js" + $verstion,
				_cmpPath + "/js/cmp-dtPicker.js" + $verstion,
				_cmpPath + "/js/cmp-search.js" + $verstion,
				_cmpPath + "/js/cmp-popPicker.js" + $verstion,
				_cmpPath + "/js/cmp-handWriteSignature.js" + $verstion,
				_cmpPath + "/js/cmp-camera.js" + $verstion,
				_cmpPath + "/js/cmp-sliders.js" + $verstion,
				_cmpPath + "/js/cmp-tabChange.js" + $verstion,
				_cmpPath + "/js/cmp-contentEdit.js" + $verstion,
				_cmpPath + "/js/cmp-flexible.js" + $verstion,
				_cmpPath + "/js/cmp-webviewListener.js" + $verstion,
				_cmpPath + "/js/cmp-emoji.js" + $verstion,
				//_cmpPath + "/js/cmp-contentSign.js" + $verstion,
				_cmpPath + "/js/cmp-encrypt.js" + $verstion,

				_wfPath + "/js/wf.js" + $verstion,	
				_collPath + "/js/details/comment_del.js" + $verstion,	
				_formPath + "/js/lib/vue/vue.js" + $verstion,	
				_formPath + "/js/dataService.js" + $verstion,	
				_formPath + "/js/sui.js" + $verstion,	
				_commonsPath + "/cmp-resources/project/js/projectAccountList.js" + $verstion,	
				_unflowform + "/unflowform_m_api.s3js" + $verstion,	
				_deePath + "/js/formDevelopmentOfadv.js" + $verstion,	
				_common_v5_path + "/widget/SeeyonAttachment.s3js" + $verstion,	
				_docPath + "/js/docNewPigeonhole.js" + $verstion,
				_common_v5_path + "/widget/ContentEdit-debug.js" + $verstion
            ]
    });

    LazyUtil.addLazyStack({
        "code" : "lazy_thispage",
        "css" : [],
        "js" : [
                _collPath + "/collaboration_m_api.s3js" + $verstion
            ]
    });

  //意见相关
    LazyUtil.addLazyStack({
        "code" : "lazy_listView",
        "css" : [
                 _cmpPath + "/css/cmp-listView.css" + $verstion,
                 _cmpPath + "/css/cmp-att.css" + $verstion
                 ],
        "js" : [
                _cmpPath + "/js/cmp-imgCache.js" + $verstion,
                _cmpPath + "/js/cmp-listView.js" + $verstion,
                _cmpPath + "/js/cmp-att.js" + $verstion,
                _collPath + "/js/mplus_apps_collaboration.s3js" + $verstion,
                _cmpPath + "/js/cmp-emoji.js" + $verstion
                ]
    });

  //添加懒加载数组
    LazyUtil.addLazyStack({
        "code" : "lazy_wf",
        "depend" : "lazy_listView",
        "dependModel" : "strong",
        "css" : [_wfPath + "/css/wf.css" + $verstion],
        "js" : [_cmpPath + "/js/cmp-zoom.js" + $verstion]
    });

    LazyUtil.addLazyStack({
    	"code" : "lazy_dee",
    	"js" : [ _deePath + "/js/formDevelopmentOfadv.js" + $verstion]
    });

    if(summaryBO.summary.bodyType =='20'
        || (summaryBO.content
                && summaryBO.content["contentType"] == SeeyonContent.getBodyCode("HTML")
                && summaryBO.content.isForwardForm)){
        LazyUtil.addLazyStack({
            "code" : "lazy_vue",
            "groups" : "seeyon_form",
            "js" : [
                    _formPath + "/js/lib/vue/vue.js" + $verstion,
                    _common_v5_path + "/cmp-resources/project/js/projectAccountList.js" + $verstion
                    ],
        });
        LazyUtil.addLazyStack({
            "code" : "lazy_form",
            "depend" : "lazy_vue",
            "dependModel" : "strong",
            "groups" : "seeyon_form",
            "css" : [
                       _formPath + "/css/index_edoc.css" + $verstion
                     ],
            "js" : [
                    _formPath + "/js/dataService.js" + $verstion,
                    _formPath + "/js/sui.js" + $verstion,
                    _unflowform + "/unflowform_m_api.s3js" + $verstion
                    ],
        });
    }else{
        LazyUtil.addLazyStack({
            "code" : "lazy_form",
            "css" : [],
            "js" : [
                    _unflowform + "/unflowform_m_api.s3js" + $verstion
                    ],
        });
        LazyUtil.addLazyStack({
            "code" : "lazy_sliders",
            "depend" : "lazy_listView",
            "css" : [
                     _cmpPath + "/css/cmp-sliders.css" + $verstion
                     ],
            "js" : [
                    _cmpPath + "/js/cmp-sliders.js" + $verstion
                    ]
        });
    }

    LazyUtil.addLazyStack({
        "code" : "lazy_edit",
        "js" : [_cmpPath + "/js/cmp-contentEdit.js" + $verstion,
                _common_v5_path + "/widget/ContentEdit-debug.js" + $verstion
                ],
    });

    //渲染一部分页面
    _fillTitle();

  //初始化处理相关
    __initDeal__(function(){

        //装载页面
        _fillPage();

        var sc = summaryBO.content;
      //开始懒加载, 轻表单需要提前加载js
        if(sc && (summaryBO.summary.bodyType =='20' || pageX.cache.isFormForward === true)){
            LazyUtil.startLazy("seeyon_form");
        }

        _bindEvent();//绑定事件
    });

    //更新listView缓存中本条记录为已读
    updateListCache(summaryBO.summary.affairId, "read");

    //添加缓存
    document.addEventListener('beforepageredirect', function(e){
        _storagePageData();
    });

    //重新渲染
    document.addEventListener('refreshWebView', function(e){

        //清空防止重复点击的变量
        _violenceClickFlag = false;
        _summaryRepeatClk = false;
        //更新删除一下缓存
        _loadSummaryCache();
    });

    //多webview事件监听
    LazyUtil.addLoadedFn("lazy_cmp", function(){
        cmp.webViewListener.addEvent(WebEvents.M3_EVENT_SUMMARY + pageX.winParams.cache_subfix,function(){//注册监听，用于改变点击的那一列数据样式和内容的改变
            //多webview事件触发
            cmp.event.trigger("refreshWebView", document);
        });
    });
	LazyUtil.addLoadedFn("form_edoc", function(){
         var pageParams = {
			"cache_subfix" : pageX.winParams.cache_subfix,
			"WebviewEvent" : WebEvents.M3_EVENT_SUMMARY + pageX.winParams.cache_subfix,
			"action" : WorkFlowLock.SUBMIT//提交操作
		}
		//公文处理界面移植到详情界面的入口
		initEdocDetail();         
    });
	
}


//渲染页面拆分
function _fillTitle(){

    if(pageX.winParams["openFrom"]=='listWaitSend' && summaryBO.summary.bodyType !='20'){
        var titleTip = cmp.i18n("collaboration.page.lable.useComputerOper");
        _$("#showTitle").innerHTML = titleTip;
    }

  //点赞
    if (!summaryBO.summary.canPraise) {
        _$("#canPraise1").style.display="none";
        _$("#canPraise2").style.display="none";
        _$("#canPraise3").style.display="none";
        _$("#canPraise4").style.display="none";
        _$("#comment_like_count").style.display="none";
    }

    //标题区域
    var titleTemplate = _$("#title_template").innerHTML;
    var titleHtml = cmp.tpl(titleTemplate, summaryBO.summary);
    _$("#title_div").innerHTML = titleHtml;

    //正文标签显示控制
    if(summaryBO.pageConfig.isShowContent == false){
        _$("#_contentBtn").style.display="none";
    }else{
        _$("#_contentBtn").style.display="block";
    }

    //全文签批标签显示控制
    _$("#contentSign").style.display = summaryBO.summary.aipFileId && cmp.os.android && !isWechat() ? "block" : "none";

    //表单多视图
    var cInfo = summaryBO.content, tabHtml ="";
    if(cInfo && cInfo.contentList && cInfo.contentList.length > 1){

        var count = cInfo.contentList.length;
        if(count > pageX.viewMax){
            //显示3.5个
            pageX.viewCtWidth = window.innerWidth;
            pageX.viewItemWidth = Math.floor(pageX.viewCtWidth / 3.5);
            pageX.viewWidth = pageX.viewItemWidth * count;
        }
        pageX.viewsLenth = count;

        var tpl = _$("#more_view_item_tpl").innerHTML;
        for(var i = 0; i < count; i++){
            var item = cInfo.contentList[i];
            item.layIndex = i;
            if(pageX.cache.formIndex == item.index){
                item.active = true;
            }else{
                //没有做拷贝， 这里是直接操作对象，所以要赋值false
                item.active = false;
            }
            if(item.isOffice == "true"){
                pageX.officeIdex = item.index;
            }
            if(pageX.viewItemWidth != 0){
                item.width = pageX.viewItemWidth + "px";
            }
            if(typeof pageX.cache.viewLight["" + item.index] === "undefined"){
                pageX.cache.viewLight["" + item.index] = item.isLightForm === "true";
            }
            tabHtml += cmp.tpl(tpl, item);
        }

        if(tabHtml){
            var c = _$("#form_views");
            c.innerHTML = tabHtml;
            if(count > pageX.viewMax){
                //显示3.5个
                c.style.width = pageX.viewWidth + "px";
            }
            c.classList.remove("display_none");
        }
    }

    //2. 转发意见
      if(summaryBO.forwordCommentList && summaryBO.forwordCommentList.length > 0){

          var forwordComs = summaryBO.forwordCommentList;

          var fSenderTpl = _$("#sender_comment_template").innerHTML;
          var fCommentTpl = _$("#forword_comment_tpl").innerHTML;
          var fLocation = _$("#forwordCommentLocaltion");

          for(var i = 0; i < forwordComs.length; i++){

              var row = forwordComs[i];
              //转发发起者附言
              var senderLabel = cmp.i18n("collaboration.summary.forword.time",[row.forwardCount,row.noteList.length]);
              cmp.tpl(fSenderTpl, row.noteList);
              var sendDatas = {
                      "id" : "forword_sender_container" + i,
                      "senderLabel" : senderLabel,
                      "titleClass" : "dropdown",
                      "bodyClass" : "white",
                      "conmentsId" : "forword_sender_list_" + i,
                      "noteList" : row.noteList
              }

              fLocation.insertAdjacentHTML("beforeBegin",cmp.tpl(fCommentTpl, sendDatas));

              (function(rList){
                //延迟加载意见
                  LazyUtil.addLoadedFn("lazy_listView", function(){
                      //意见附件
                      _rendSendCommentAttr(rList);
                      rList = null;
                  });
              })(row.noteList);

              _addToggleEvent(sendDatas.id);

              //转发意见
              var cLabel = cmp.i18n("collaboration.summary.forword2zan.time",[row.forwardCount,row.replysList.length,row.zanCount]);
              var listDatas = {
                      "id" : "forword_comments_container" + i,
                      "senderLabel" : cLabel,
                      "titleClass" : "",
                      "bodyClass" : "white",
                      "conmentsId" : "forword_comments_list_" + i,
                      "noteList" : {}
              }
              fLocation.insertAdjacentHTML("beforeBegin",cmp.tpl(fCommentTpl, listDatas));
              (function(replysList, conmentsId, id){
                  //延迟加载意见
                    LazyUtil.addLoadedFn("lazy_listView", function(){
                        __rendList(replysList, conmentsId, false, true, id);
                        replysList = null;
                        conmentsId = null;
                        id = null;
                    });
                })(row.replysList, listDatas.conmentsId, listDatas.id);

              _addToggleEvent(listDatas.id);

              if(row.noteList == 0){
                  _$("#"+sendDatas.id).remove();
              }
          }
      }

    //3. 发起人附言
      var senderComments = summaryBO.senderCommonts;
      if(senderComments && senderComments.length > 0){

          var senderCommentHtml = cmp.tpl(_$("#sender_comment_template").innerHTML, senderComments);

          _$("#sender_comment_ul").insertAdjacentHTML("beforeEnd",senderCommentHtml);
          _$("#sender_comment_count").innerText = senderComments.length;

        //延迟加载意见
          LazyUtil.addLoadedFn("lazy_listView", function(){
            //意见附件
              _rendSendCommentAttr(senderComments);
              senderComments = null;
          });

          _$("#sender_comment_container").classList.remove("display_none");
          _addToggleEvent("sender_comment_container");

          //新增附言
          _showSenderComment(summaryBO.pageConfig.canAddSenderComment);
      }else{
          if(!summaryBO.pageConfig.canAddSenderComment){
              _$("#sender_comment_container").remove();
          }else{

              pageX.toggleLableCount += 1;

              var sc = _$("#sender_comment_container");
              sc.querySelector('[class*="see-icon-v5-common-arrow"]').remove();
              sc.classList.remove("display_none");
              //新增附言
              _showSenderComment(summaryBO.pageConfig.canAddSenderComment);
          }
      }

      if(summaryBO.allCommentCount > 0){

          var $comentContainer,$Container,cClassList;

          $comentContainer = _$("#comments_container");
          $Container = _$("#comments_container");
          cClassList = $Container.classList;

         /*
          * 意见更多页面屏蔽，但是先别删代码，产品经理可能会后悔
          *
          * $comentContainer.querySelector("#more_comment_btn").addEventListener("tap", function(e){
		    e.stopPropagation();
			_formLoadCheck({
        		        checkCallback : function(ret){
        		            if(ret == true){
        		            	//TODO 如果是非编辑状态下就不需要这个判断了
        		            	//表单校验判断
        		                if(summaryBO.pageConfig.canDeal
        		                        && summaryBO["summary"].bodyType == "20"){
        		                    if(cmp.sui.isPreventSubmit()){
        		                        //表单失去焦点校验失败,阻止跳转
        		                        return;
        		                    }
        		                }

        		                var pageParams = {
        		                        "cache_subfix" : pageX.winParams.cache_subfix,
        		                        "WebviewEvent" : WebEvents.M3_EVENT_SUMMARY + pageX.winParams.cache_subfix,
        		                    }
        		                summaryBO.backIndex = summaryBO.backIndex + 1;
        		                cmp.event.trigger("beforepageredirect", document);
        		                cmp.href.next(_collPath + "/html/details/moreComment.html"+colBuildVersion, pageParams, {openWebview : true});
        		            }
        		        }
        		    });



          });*/


          $comentContainer.querySelector("#comment_like_count").innerText = summaryBO.likeCommentCount;

          $Container.querySelector("#comment_count").innerText = summaryBO.allCommentCount;

          //显示意见
          cClassList.remove("display_none");

          pageX.toggleLableCount++;
          _addToggleEvent("comments_container");

        //延迟加载意见
          LazyUtil.addLoadedFn("lazy_listView", function(){
            //加载全部意见
              _initListView(true);
          });

        //回复和点赞设置
          if(summaryBO.pageConfig.canReply){
              _showReplyBtns("#comments_container");
          }
      }else{
        //延迟加载意见
          LazyUtil.addLoadedFn("lazy_listView", function(){
            //加载全部意见
              _initListView(false);
          });
      }
}

//装载页面
function _fillPage() {

  //多视图展现
    if(summaryBO["summary"].bodyType == '20'){
        _initFormViews();
    }
	  //判断该节点移动端是否能够处理
    if(!summaryBO["summary"].isCanHandle){
    	if(_$("#handleBtns")){
       	 _$("#handleBtns").style.display="none";
       	}
    	if(_$("#otherBtns")){
    		 _$("#otherBtns").style.display="none";
    	}
    	if(_$("#prompt")){
    		_$("#prompt").style.display="";
			_$("#hand_first_line").style.display="none";
			_$("#button_list_nav_new").style.display="none";
			
    	}
          if(_$("#footer_btns")){
        	  _$("#footer_btns").style.backgroundColor="rgb(255,249,233)";
          }

    }


  //初始化正文区域
    _initLayout(false);
    _toggleContent(false);

    //尝试加载正文
    _initContent();
}


//存储状态数据
function _storagePageData(){

    if(pageX.viewScroll && pageX.viewsLenth > pageX.viewMax){
        pageX.cache.scollLeft = pageX.viewScroll.x;
    }

	cmp.storage.save(_storge_key, cmp.toJSON(pageX.cache), true);
}


//设置元素布高度等
function _initLayout(isRefresh, tHeight, setTitle){

  //设置正文区域高度
    var $title = _$("#summary_titile_container"),
        bodyHeight = 0,
        tagHeight = 55,//_$("#contentAndWfTags").offsetHeight
        formViewHeight = pageX.viewsLenth > 0 ? 36 : 0,//_$("#form_views")
        lHeight = pageX.toggleLableCount != 0 ? 50 : 0,
        titleHeight = 0,
        headerH = 0;

    //优化渲染数度
     var headerDom = _$("#page_header");
    var hStyleHeight = headerDom.style.height;
    if(hStyleHeight){
        headerH = parseInt(hStyleHeight, 10);
    }else{
        //offsetHeight 优化渲染
        headerH =  headerDom.offsetHeight;
        headerDom.style.height = headerH + "px";
    }

    var $bodyContent = _$("#body_content_div");
    var bStyleHeight = $bodyContent.style.height;
    if(bStyleHeight){
        bodyHeight = parseInt(bStyleHeight, 10);
    }else{
        //offsetHeight 优化渲染
        bodyHeight =  $bodyContent.offsetHeight;
        $bodyContent.style.height = bodyHeight + "px";
    }

    if(typeof tHeight != "undefined" && tHeight != null){
        titleHeight = tHeight;
    }else{
        var tStyleHeight = $title.style.height;
        if(tStyleHeight){
            titleHeight = parseInt(tStyleHeight, 10);
        }else{
            //offsetHeight 优化渲染
            titleHeight =  $title.offsetHeight;
        }
    }

    var fHeight = 0;
    var foot = _$("#footer_btns");
    if(foot){
        fHeight += foot.offsetHeight;
    }

    var handleContentHeight = 0;
    $handContent = _$("#hand_first_line");
    if($handContent && !$handContent.classList.contains('display_none')){
        handleContentHeight = parseInt($handContent.style.height, 10) - $("#sender_comment_container").outerHeight(true);
    }

    var cHeight = bodyHeight - titleHeight - tagHeight - formViewHeight - lHeight - fHeight + handleContentHeight;
   /* _$("#newInputPosition").style.height = cHeight + "px";
    _$("#form_body").style.height = cHeight + "px";*/
    _$("#summary_info").style.height = cHeight + "px";
    pageX.contentHeight = cHeight;

    if(!isRefresh){

        if(setTitle !== false){
            $title.style.height = titleHeight + "px";
            $title.setAttribute("data-orgheight", titleHeight);
        }

        var $contentView = _$("#contentView");
        $contentView.style.height = (bodyHeight - fHeight - tagHeight - formViewHeight) + "px";
        $contentView.setAttribute("data-mintop", tagHeight + headerH + formViewHeight - 11);
        $contentView.setAttribute("data-maxtop", bodyHeight - fHeight - lHeight + headerH);
    }
}


//附件区域显示和影藏
function _toggleContent(show){

	var tContentViewEl = _$("#contentView");
    if(pageX.toggleLableCount == 0){
        //没有意见
    	tContentViewEl.style.display = "none";
        return;
    }else{
    	tContentViewEl.style.display = "";
    }

    var cHeight = 0,
        tClass = tContentViewEl.classList;

    if(show){
        if(!tClass.contains("comment_animation")){
            tClass.add("comment_animation");
        }
        cHeight = tContentViewEl.getAttribute("data-mintop");
        pageX.isComentShow = true;
        _toggleTitle(false, "byContent");
    }else{
        if(tClass.contains("comment_animation") && !pageX.isComentShow){
            tClass.add("comment_animation");
        }
        cHeight = tContentViewEl.getAttribute("data-maxtop");
        pageX.isComentShow  = false;
        _toggleTitle(true, "byContent");
    }
    tContentViewEl.style.top = parseInt(cHeight) + "px";
}

/**
 * 影藏标题区域
 */
function _toggleTitle(show, tFrom){

    var $title = _$("#summary_titile_container"),
        tHeight = 0,
        nowHeight = $title.style.height,
        formCode = tFrom + "-show";

    if(show){
        tHeight = parseInt($title.getAttribute("data-orgheight"), 10);
    }

    if(nowHeight != (tHeight + "px")){

        var toLayout = true;
        if(tFrom){
            if(!show){
                $title.setAttribute(formCode, "1");
            }else{
                if("1" != $title.getAttribute(formCode)){
                    toLayout = false;
                }
                $title.setAttribute(formCode, "0");
            }
        }
        if(toLayout){
            if(!$title.classList.contains("title_animation")){
                $title.classList.add("title_animation");
            }
            $title.style.height = tHeight + "px";
            _initLayout(true, tHeight);
            if(tFrom != "byContent"){
                _toggleContent(false);
            }
            if(summaryBO["summary"].bodyType == "20"){

                setTimeout(function(){
                    SeeyonContent.reLayout("newInputPosition", pageX.contentHeight);
                }, 10);
            }
        }
    }
}


//加载意见列表
function _initListView(pageLoad){

    var listParam = {
            imgCache:true,
            offset:{
                x:0,
                y:window.innerHeight - 150
            },
            config : {
                purpose:-1,//list为空的时候，组件会清空容器，设置不清空
                customScrollMoveEvent: function (scrollY) {  //启用自定义时，其他参数不要传
                    if(scrollY > 30){
                        _toggleContent(false);
                    }
                }
            },
            onBeforeScrollMove : function(){
                if(!pageX.isComentShow){
                    _toggleContent(true);
                }
            }
        }

    //需要加载数据
    if(pageLoad){
        listParam = cmp.extend(true, listParam, {
            up: {
                contentdown: cmp.i18n("collaboration.page.lable.load_more"),//加载更多
                contentrefresh: cmp.i18n("collaboration.page.lable.load_ing"),//加载中...
                contentnomore: cmp.i18n("collaboration.page.lable.load_nodata")//没有更多
            },
            down: {
                contentdown: cmp.i18n("collaboration.page.lable.load_more"),//加载更多
                contentrefresh: cmp.i18n("collaboration.page.lable.load_ing"),//加载中...
                contentnomore: cmp.i18n("collaboration.page.lable.load_nodata")//没有更多
            }
        });
        listParam.config = cmp.extend(true, listParam.config, {
            pageSize : 20,
            params : {
                "type" : "all",
                "summaryId" :  summaryBO.summary.id,
                "affairId" : summaryBO.summary.affairId,
                "openFrom" : pageX.winParams["openFrom"]
            },
            dataFunc : _getCommentDataList,
            renderFunc : _renderCommentData
        });
    }

	cmp.listView("#contentView", listParam);

	if(!pageLoad){
	   setTimeout(fnRefreshPage, 500);
	}
}

//分页获取所有意见
function _getCommentDataList(pDatas, options) {

    $s.EdocResource.summaryComment(pDatas["type"], pDatas["summaryId"], pDatas, errorBuilder({
        success : function(result) {
            var successFn = options.success;
            successFn(result);
        }
    }));
}

//数据展现
function _renderCommentData(result, isRefresh) {


    __rendList(result, "summary_comment_ul", summaryBO.pageConfig.canReply, isRefresh, "");

    //刷新页面
    setTimeout(fnRefreshPage, 500);
}

/**
 * 发起者附言，或者转发附言附件初始化
 */
function _rendSendCommentAttr(comments){
  //意见附件
    for(var i = 0; i < comments.length; i++){
        var comment = comments[i];
        var attrsArray = comment["attachments"] || "[]";
        var attrs = cmp.parseJSON(attrsArray);
        if(attrs.length > 0){
            CollUtils.initAttStyle("#senderCommentAttr" + comment.id, attrs);
        }else{
            _$("#senderCommentAttr" + comment.id).remove();
        }
    }
}



/**
 * 为附件等添加切换事件
 */
function _addToggleEvent(itemId){

    var el = _$("#" + itemId);
    if(el){

        pageX.toggleLableCount += 1;

        el.querySelector(".attach-title").addEventListener("tap", function(){

            if(!pageX.isComentShow){
                _toggleContent(true);
                return;
            }

            var eBody = this.nextElementSibling;
            var eClass = eBody.classList;
            if (eClass.contains('display_none')) {
                eClass.remove('display_none');
            }else{
                eClass.add('display_none');
            }

            var icon = this.querySelector('[class*="see-icon-v5-common-arrow"]');
            var iClass = icon.classList;
            if(!iClass.contains("see-icon-v5-common-arrow-right")){

                var iRClass = 'see-icon-v5-common-arrow-top';
                var iAClass = 'see-icon-v5-common-arrow-down';
                if (iClass.contains(iAClass)) {
                    var tAClass = iRClass;
                    iRClass = iAClass;
                    iAClass = tAClass;
                }

                iClass.remove(iRClass);
                iClass.add(iAClass);
            }

            fnRefreshPage();
        });
    }
}

//绑定事件
function _bindEvent(){

    //工作流展现
    _$("#workflowBtn").addEventListener("tap", _showWorkflow);

  //正文展现
    _$("#_contentBtn").addEventListener("tap", _showConent1);

    //附件列表展现
    _$("#attachmentBtn").addEventListener("tap", function () {
        var paramData = {
            "summaryBO" : summaryBO,
			"cache_subfix" : pageX.winParams.cache_subfix,
        }
		cmp.event.trigger("beforepageredirect", document);
        cmp.href.next(_collPath + "/html/details/attachmentList.html?r="+Math.random(), paramData);
    });

    //全文签批展现
    _$("#contentSign").addEventListener("tap", function () {
        _downloadContentSignFile(summaryBO.summary.aipFileId);
    });

    //此处监听sui_form_customcontrol_render事件，当表单中自定义控件发生渲染时，会触发此事件
    document.addEventListener('sui_form_customcontrol_render', function(e){
    	_customcontrol_meetingroom_init(e);
    });
}

//处理人列表
function _initHandlerList(type){
    var nextPageData = {
            "tab" : type,
            "allCount" : summaryBO.affairCount.all,
            "runningCount" : summaryBO.affairCount.running,
            "affairId" : summaryBO.summary.affairId,
            "summaryId" : summaryBO.summary.id,
            "canHasten" : summaryBO.pageConfig.canHasten,
            "cache_subfix" : pageX.winParams.cache_subfix,
            "WebviewEvent" : WebEvents.M3_EVENT_SUMMARY + pageX.winParams.cache_subfix,
        };
    cmp.event.trigger("beforepageredirect",document);
    cmp.href.next(_collPath + "/html/details/handler_details.html"+colBuildVersion, nextPageData, {openWebview : true});
}

/**
 * 展现流程图
 */
function _showWorkflow(){

	 _formLoadCheck({
	        checkCallback : function(ret){
	            if(ret == true){
	            	//TODO 如果是非编辑状态下就不需要这个判断了
	            	//表单校验判断
	                if(summaryBO.pageConfig.canDeal
	                        && summaryBO["summary"].bodyType == "20"){
	                    if(cmp.sui.isPreventSubmit()){
	                        //表单失去焦点校验失败,阻止跳转
	                        return;
	                    }
	                }
	                if(_summaryRepeatClk){
                        return;
                    }
                    _summaryRepeatClk = true;
	                //这里传参要和点击处理一致, 表单有office正文不允许处理
	                var pageParams = {
	                    "canEditWorkflow" : ((cmp.getForwardTo && cmp.getForwardTo() != null) || summaryBO.formIsLock === true)  ? false : pageX.viewCanEdit,
	                    "action" : WorkFlowLock.SUBMIT,//提交操作
	                    "cache_subfix" : pageX.winParams.cache_subfix,
	                    "WebviewEvent" : WebEvents.M3_EVENT_SUMMARY + pageX.winParams.cache_subfix,
                        "edit": true,
                        "canBack":false
	                }
	                summaryBO.backIndex = summaryBO.backIndex + 1;
	                cmp.event.trigger("beforepageredirect", document);
	                cmp.href.next(_collPath + "/html/details/workflowEdit.html"+colBuildVersion, pageParams, {openWebview : true});
	            }
	        }
	    });
}

/**
 * 展现流程图
 */
function _showConent1(){
	var pageParams = {
            "canEditWorkflow" : ((cmp.getForwardTo && cmp.getForwardTo() != null) || summaryBO.formIsLock === true) ? false : pageX.viewCanEdit,
            "action" : WorkFlowLock ? WorkFlowLock.SUBMIT : 14,//提交操作
            "cache_subfix" : pageX.winParams.cache_subfix,
            "WebviewEvent" : WebEvents.M3_EVENT_SUMMARY + pageX.winParams.cache_subfix,
            "summaryBO":summaryBO
        };
	var content = summaryBO.content1;
		var content1bodyType = content["contentType"];
		 if(46 ==content1bodyType){
            cmp.notification.alert("暂不支持OFD正文");
            return;
        }
		if(content1bodyType != SeeyonContent.getBodyCode("HTML") ){
            var suffixMap = {
                    "wps" : "doc",
                    "et" : "xls"
             }
            var subfix = SeeyonContent.getBodyType(content1bodyType);
            var newFileName = "";
            var newSuffix = suffixMap[subfix] || subfix;

            if(cmp.platform.CMPShell){
                var fileName = newFileName || (cmp.i18n("commons.label.defTitle") + "." + newSuffix);
                var downFilePath = cmp.origin + "/rest/attachment/file/" + content.fileId + "?fileName=" + encodeURI(fileName);
                var option={
                    path : downFilePath,
                    filename : fileName,
                    extData:{
                        fileId:content.fileId,
                        lastModified:content.lastModified,
                        isClearTrace:true
                    },
                    success: function(res){
                        cmp.dialog.loading(false);
                    },
                    error:function(err){
                        cmp.dialog.loading(false);
                        if(err.code==17002){
                        	this.alert(cmp.i18n("commons.note.file.notorremoved"));
                        }else if(err.code==500){
                        	if(err.message){
                        		this.alert(err.message);
                        	}else{
                        		this.alert(cmp.i18n("commons.server.error.tip"));
                        	}
                        }else{
                        	//this.alert(cmp.i18n("commons.note.readcontenterror", [JSON.stringify(err)]));//读取正文失败, 请稍重试.错误信息:
                        }
                    }
                }
                //如果有修改正文的策略和wps授权码，编辑正文界面
                if(!summaryBO.content1
                    || !summaryBO.canEditContent
                    // || summaryBO.content1.contentType=="20"
                    || !summaryBO.content1.fileId
                    || !CollUtils.isCMPShell()
                    || !cmp.os.android){
                    //参考comment.js中修改正文策略提交代码
					//查看正文
					cmp.att.read(option);
                }else{
                    androidEditOrReadContent(null,option);
                }

            }else{
                var srcFileName = newFileName || (cmp.i18n("commons.label.defTitle") + "." + newSuffix);
                var fileName = srcFileName;
                fileName = encodeURI(fileName);
                var downFilePath = cmp.origin + "/rest/attachment/file/" + content.fileId + "?fileName=" + fileName;
                if(cmp.att.canDownload4Wechat(newSuffix)){
                    cmp.att.download({"url": downFilePath, "title" : srcFileName});
                }else{
                   cmp.notification.toast(cmp.i18n("commons.note.notsuport3"), 'top', 1000);
                }
                //$.notification.toast($.i18n("commons.note.notsuport3"), 'top', 1000);//微信端暂不支持该正文查看!
            }

        return;
		}
        summaryBO.backIndex = summaryBO.backIndex + 1;
        cmp.event.trigger("beforepageredirect", document);
        cmp.href.next(_collPath + "/html/details/_showContent.html"+colBuildVersion, pageParams, {openWebview : true});
}

//office格式的正文修改
function androidEditOrReadContent(readOnly, option){
    var fileType=option.filename.substring(option.filename.lastIndexOf(".") + 1, option.filename.length);
    if("pdf"==fileType){
        //判断是否pdf圈阅授权(获取序列号)
        $s.EdocResource.getPdfAuthKey({},{},errorBuilder({
            success : function(result) {
                if(result && result.authKey && (summaryBO.pageConfig && summaryBO.pageConfig.canEditContent)){
                    summaryBO.copyRight = result.authKey;
                    summaryBO.type = "newEdoc";
                    summaryBO.readOnly = readOnly;
                    summaryBO.isClearTrace = true;
                    if(!readOnly){
                        //修改正文时加锁
                        WorkFlowDesignerUtil.lockH5Workflow(summaryBO["summary"].id, WorkFlowLock.EDIT_CONTENT, function(ret) {
                            if(ret) {
                                LazyUtil.addLoadedFn("lazy_edit", function(){
                                    ContentEdit.init(summaryBO);
                                });
                            }else{//如果pc端正在修改正文，M3就只能查看正文，不能编辑
                                cmp.att.read(option);
                            }
                        });
                    }else{
                        LazyUtil.addLoadedFn("lazy_edit", function(){
                            ContentEdit.init(summaryBO);
                        });
                    }
                }else{
                    //如果没有授权码，直接弹出打开正文界面
                    cmp.dialog.loading();
                    //TODO 暂时没涉及到正文修改；
                    /*if(typeof(summaryBO) != "undefined"){//如果当前修改过正文，取修改正文后的文件
                     if(summaryBO.editParam){
                     option.path = summaryBO.editParam.filepath;
                     }
                     }*/
                    cmp.att.read(option);
                    // _alert(cmp.i18n("collaboration.edit.office.content.authorization"));
                }
            }
        }));
    }else{
        //判断是否移动授权(获取序列号)
        $s.EditContent.getOfficeAuthKey({},{},errorBuilder({
            success : function(result) {
                if(result && result.officeAuthKey && (summaryBO.pageConfig && summaryBO.pageConfig.canEditContent)){
                	summaryBO.officeLicense = result;
                    summaryBO.type = "newEdoc";
                    summaryBO.readOnly = readOnly;
                    summaryBO.isClearTrace = true;
                    if(!readOnly){
                        //修改正文时加锁
                        WorkFlowDesignerUtil.lockH5Workflow(summaryBO["summary"].id, WorkFlowLock.EDIT_CONTENT, function(ret) {
                            if(ret) {
                                LazyUtil.addLoadedFn("lazy_edit", function(){
                                    ContentEdit.init(summaryBO);
                                });
                            }else{//如果pc端正在修改正文，M3就只能查看正文，不能编辑
                                cmp.att.read(option);
                            }
                        });
                    }else{
                        LazyUtil.addLoadedFn("lazy_edit", function(){
                            ContentEdit.init(summaryBO);
                        });
                    }
                }else{
                    //如果没有授权码，直接弹出打开正文界面
                    cmp.dialog.loading();
                    //TODO 暂时没涉及到正文修改；
                    /*if(typeof(summaryBO) != "undefined"){//如果当前修改过正文，取修改正文后的文件
                     if(summaryBO.editParam){
                     option.path = summaryBO.editParam.filepath;
                     }
                     }*/
                    cmp.att.read(option);
                    // _alert(cmp.i18n("collaboration.edit.office.content.authorization"));
                }
            }
        }));
    }
}


//表单视图切换时页面布局
function _layout4formView(tValue, reLayout){
    var foot = _$("#footer_btns");
    if(foot && summaryBO["summary"].listType != "onlyView" && summaryBO.pageConfig.canDeal){
        /** 意见更多页面屏蔽，但是先别删代码，产品经理可能会后悔 **/
    	/*var mcb = _$("#more_comment_btn");*/
        var oldDisplay = foot.style.display
        if(tValue != "0"){
            pageX.viewCanEdit = false;
            //只有第一个视图可以处理
            foot.style.display = "none";
            /*if(mcb){
            	mcb.style.display = "none";
            }*/
        }else{
            foot.style.display = "";
            pageX.viewCanEdit = true;
            /*if(mcb){
            	mcb.style.display = "";
            }*/
        }
        if(reLayout !== false && oldDisplay != foot.style.display){
            _initLayout(false, null, false);
            _toggleContent(false);
        }
    }
}

/**
 * 表单多视图进行切换
 */
function _switche2View(index, toConfirm){

    if(pageX.viewsLenth < 1){
        return;
    }

    var tabIndex, _this, isoffice, leaveOffice, classname, tabsContainer;

    tabsContainer = _$("#form_views");
    if(typeof index == "object"){
        _this = index;
    }else{
        _this = _$("li[index='" + index + "']", false, tabsContainer);
    }

    tabIndex = _this.getAttribute("index");
    isoffice = _this.getAttribute("isOffice") == "true";
    leaveOffice = pageX.cache.focusOffice && !isoffice;
    classname = "selected";

    if(tabIndex != pageX.cache.formIndex || leaveOffice){

        function callback(){

            //切换tab
            var tabs = tabsContainer.querySelectorAll("li");
            for(var k = 0, len = tabs.length; k < len; k++){
                var t = tabs[k];
                if(t.classList.contains(classname)){
                    t.classList.remove(classname);
                }
            }
            _this.classList.add(classname);
            //滚动页签到可视区域
            if(pageX.viewScroll){
                var minX, maxX,begin,layIndex, toX;

                layIndex = parseInt(_this.getAttribute("layIndex"), 10);
                minX = Math.abs(pageX.viewScroll.x);
                maxX = minX + pageX.viewCtWidth;
                begin = layIndex * pageX.viewItemWidth;
                end = begin + pageX.viewItemWidth;
                if(minX > end || end > maxX){
                    toX = -Math.min(begin, pageX.viewWidth - pageX.viewCtWidth);
                    pageX.viewScroll.scrollTo(toX, 0);
                }
            }

            if(isoffice){
                if(!pageX.cache.focusOffice){
                    pageX.cache.focusOffice = true;
                    _$("#newInputPosition").style.display = "none";
                    _$("#form_body").style.display = "";
                }
            }else{
                if(pageX.cache.focusOffice){
                    pageX.cache.focusOffice = false;
                    _$("#newInputPosition").style.display = "";
                    _$("#form_body").style.display = "none";
                }
            }

            if(isoffice){
                //初始化正文
                SeeyonContent.init({
                    "target" : "form_body",
                    "bodyType" : SeeyonContent.getBodyCode(_this.getAttribute("extension")),
                    "content" : _this.getAttribute("fileId"),
                    "moduleType" : "1",
                    "lastModified" : _this.getAttribute("lastModified")
                });
            }else if(tabIndex != pageX.cache.formIndex){

                _cacheSignet(true);//缓存签章

                var  _tIsLightForm = pageX.cache.viewLight["" + tabIndex];//_this.getAttribute("isLightForm") === "true";
                //加载表单数据
                SeeyonContent.instance("newInputPosition").loadForm(tabIndex,{
                    isLightForm : _tIsLightForm,
                    loadCallback : function(){

                        _layout4formView(tabIndex);
                        pageX.cache.formIndex = tabIndex;
                        pageX.cache.isLightForm = _tIsLightForm;

                        //if(pageX.cache.isLightForm){//轻表单切换视图
                            initSignet();
                        //}
                    }
                });
            }
        }

        if(toConfirm === true){
            //切换表单视图移除新盖的印章
            LazyUtil.addLoadedFn("lazy_iSignaturePhone", function(){
                deleteSignatureButton(callback);
            });
        }else{
            callback();
        }
    }
}

//表单多视图展示
function _initFormViews(){

    if(pageX.cache.formIndex != "0") {
        _layout4formView(pageX.cache.formIndex, false);
    }

  //切换视图
    if(pageX.viewsLenth > 0){
        LazyUtil.addLoadedFn("lazy_listView", function(){
            cmp("#form_views").on("tap", "li", function(){
                _switche2View(this, true);
            });
        })
    }

    if(pageX.viewsLenth > pageX.viewMax){
        LazyUtil.addLoadedFn("lazy_listView", function(){
          //滚动
            pageX.viewScroll = new cmp.iScroll(_$("#form_view_container"), {
                hScroll: true,
                vScroll: false,
                x: pageX.cache.scollLeft,
                y: 0,
                bounce: false,
                bounceLock: false,
                momentum: true,
                lockDirection: true,
                useTransform: true,
                useTransition: true,
                handleClick: true
            });
        });
    }

    //Office正文
    if(summaryBO.pageConfig.canDeal){
        var $handleBtns = _$("#handleBtns") || _$("#otherBtns");
        if($handleBtns){
            $handleBtns.style.display = "";
        }

    }
}

//返回上一个页面
function _goBack(){

    //异常删除点击了返回的情况, 解决微协同打开office查看，返回时页面跳转问题
    if(cmp.href.backAbnormal()){
        return;
    }
    //防止爆点
    if(pageX.exeLock){
        return;
    }
    pageX.exeLock = true;

    //触发删除缓存
    cmp.event.trigger("deletesessioncache", document);
    if(window.summaryBO && summaryBO["summary"].bodyType == "20"){
    	if(cmp.sui && typeof cmp.sui.clearCache == "function"){
    	    var options = {
                    moduleId:summaryBO["summary"].id,
                    rightId:summaryBO["summary"].rightId,
                    viewState: summaryBO._viewState
            }
    	    cmp.sui.clearCache(options);
    	}
    }

    //解锁
    unlockCollAll(function(){
        var backN = 1;
        if(window.summaryBO && summaryBO.backIndex){
            backN += summaryBO.backIndex;
        }

        if(backN > 1){
            setListViewRefresh("true");
            cmp.href.back(backN);
        }else{
        	if(pageX.winParams && pageX.winParams.fromXz && pageX.winParams.fromXz != ""){
				cmp.href.closePage();
			}else{
				cmp.href.back();
			}
        }
    });
}


function _initBackEvent(){
	cmp.backbutton();
    cmp.backbutton.push(_initContinueFinish);
    _$("#goAheadBtn").addEventListener("tap", _initContinueFinish);
    cmp.event.listenClosePage(_initContinueFinish);
}

function _initContinueFinish() {

    //校验是否做了编辑
	if(pageX.editWorkflow === true ||
	        CollUtils.loadCache(CollCacheKey.summary.comment + pageX.winParams.cache_subfix, false) != null) {
		//是否放弃处理
		var items = [{key:"yesFinish",
		              name:"<span style='color:#ff0000'>" + cmp.i18n("collaboration.page.lable.abandonDeal") + "</span>"
		              }]; //放弃处理
	    cmp.dialog.actionSheet(items, cmp.i18n("collaboration.page.lable.button.cancel"),function (data){
	    	if(data.key=="yesFinish") {
	    		setListViewRefresh("false");
	    		_goBack();
	    	}
	    });
	} else {
		setListViewRefresh("false");
		_goBack();
	}
}

//协同解所有锁
function unlockCollAll(callback) {

    var lockAffairId = pageX.winParams.affairId;

    if (window.summaryBO) {
        if(summaryBO.pageConfig && summaryBO.pageConfig.canDeal){
            lockAffairId = summaryBO["summary"].affairId;
        }else{
            lockAffairId = null;
        }
    }

    if(!pageX.isInitError && pageX.winParams.openFrom == "listPending" && lockAffairId && lockAffairId != "-1"){
        cmp.dialog.loading(true);

    	try {
    		$s.EdocResource.unlockNewEdoc({"summaryId":summaryBO["summary"].id},{
    	        success: function(result) {
    	        	 callback();
    	        },
    	        error: function(err){
    	        	 callback();
    	        }
    	    });
    	} catch(e) {callback();}

    }else{
        callback();
    }
}

/**
 * 缓存签章dom
 */
function _cacheSignet(isClearSignet){
    var signets, signetHTML = "";
    signets = _$(".signatureImgDiv", true, _$("#newInputPosition"));
    var __signets = [];
    var ids = signatureId.split(',');
    if(signets && signets.length > 0){
    	//当前操作签的章，切换视图时会清除，轻原表单切换时不会清除
    	if(ids && ids.length>1 && isClearSignet){
    		for(var i = 0; i < signets.length; i++){
    			var isNewSignet = false;
    			for(var j = 0; j<ids.length-1;j++){
		        	if(signets[i].id.indexOf(ids[j])!="-1"){
		        		isNewSignet = true;
		        	}
    			}
    			if(!isNewSignet){
    				__signets.push(signets[i]);
    			}
    		}
    		if(__signets && __signets.length > 0){
    			for(var i = 0; i<__signets.length;i++){
    				signetHTML += __signets[i].outerHTML;
    			}
    		}
    	}else{
    		if(signets && signets.length > 0){
    			for(var i = 0; i<signets.length;i++){
    				signetHTML += signets[i].outerHTML;
    			}
    		}
    	}
    }
    pageX.cache.signets = iSP.signatures;
    pageX.cache.thatObj = iSP.getThisObj();
    pageX.cache.signetDom = signetHTML;
    pageX.cache.signetFieldDom = _$("#protectData").innerHTML;
}

function initSignet(){//初始化签章控件

    LazyUtil.addLoadedFn("lazy_iSignaturePhone", function(){
        if(pageX.cache.signetDom){

            _$("#newInputPosition").insertAdjacentHTML("beforeEnd", pageX.cache.signetDom);
            _$("#protectData").innerHTML = pageX.cache.signetFieldDom;
            if(pageX.cache.signets){
            	var _isignatureIds = _$(".signatureImgDiv",true);
            	for(var i = 0; i<_isignatureIds.length;i++){
            		iSP.reBindEvent(_isignatureIds[i].getAttribute("signatureId"),pageX.cache.signets,pageX.cache.thatObj);
            	}
            }
        }else{


            function _doShowSign(formData){
                var protectData = $("#protectData");
                var _data = "";
                if(protectData.text() == ""){//如果已经生成了dom
                    if(formData){
                        for(var key in formData ){
                            _data = formData[key].data;
                            if(formData[key].fieldType=="select" && formData[key].data==""){
                                _data = ["0"];
                            }
                            protectData.append($("<span id = 'my:"+key+"' style='display: none'></span>").text(_data.join(";")));
                        }
                    }
                }
                var _canDeal = false;
                if(_$("#handleBtns") && pageX.winParams["openFrom"] !="glwd" && pageX.winParams["openFrom"] !="docLib"){
                    _canDeal = true;
                }
                initIsignature(summaryBO.summary.id, _canDeal);
            }


            function protectDomIsLoad(){
            	var protectData = $("#protectData");
            	if(protectData.text() != "" || !summaryBO.content.isForwardForm){
            		var tFormData = null;
            		_doShowSign(tFormData);
            	}else{
            		setTimeout(function(){
            			protectDomIsLoad();
            		}, 10);
            	}
            }

            if(summaryBO["summary"].bodyType == "20"){
                LazyUtil.addLoadedFn("lazy_form", function(){
                    var tFormData = null;
                    try{
                        tFormData = cmp.sui.getFormProtectedData();
                    }catch (e) {
                        console.error("加载签章数据报错, e=" + e);
                    }
                    _doShowSign(tFormData);
                });
            }else{
                protectDomIsLoad();

            }
        }
    });
}

//注册成全局的，原表单也会调用
function onContentScollButton(){

    //正文未加载后才执行
    if(_isContentInit){
        if(pageX.toggleLableCount != 0){
            _toggleContent(true);//展示意见区域
        }
    }
}

//注册成全局的，原表单也会调用
function onContentScollTop(top, directionY){

    //正文未加载后才执行
    if(_isContentInit){

        if(!arguments || arguments.length == 0){
            _toggleTitle(true);
        }else{
            //-1下拉， 1上拉
            if(directionY == -1 && top < 10){
                _toggleTitle(true);
            }else if(directionY == 1 && top > 10){
                _toggleTitle(false);
            }
        }
    }
}

//正文加载完成后方法
function _contentInit(){

    cmp.dialog.loading(false);

    if(window.summaryBO.info_msg){
        _alert(window.summaryBO.info_msg);
        delete window.summaryBO.info_msg;
    }

    initSignet();
    _isContentInit = true;

    if(pageX.cache.focusOffice){
        //正文初始化时，不是在正文页签
        pageX.cache.focusOffice = false;
        _switche2View(pageX.officeIdex, false);
    }

  //启动正文后面的问价
    LazyUtil.startLazy();
}

//加载正文
function _initContent(){

    //重复加载正文判定
    if(pageX.initContent){
        return;
    }
    pageX.initContent = true;

    var bodyType, content;

    content = summaryBO.content;

    if(content != null){

        if(typeof pageX.cache.isLightForm != "boolean"){
            pageX.cache.isLightForm = !!content["isLightForm"];
        }

        bodyType = content["contentType"];


        var contentConfig = {
                "target" : "newInputPosition",
                "bodyType" : bodyType,
                "content" : "",
                "moduleType" : "4",//这个地方只能是公文
                "momentum" : true,
                "onload" : _contentInit,
                //"onScrollBottom" : onContentScollButton, 屏蔽这个方法， 不自动拉起意见了
                "onScroll" : onContentScollTop
            }

        //正文
        if(bodyType == SeeyonContent.getBodyCode("HTML") && !content.isForwardForm){
            //HTML正文
            contentConfig.content = content["contentHtml"];
            contentConfig.ext = {
                    reference : summaryBO.summary.id
            }
        }else if(bodyType == SeeyonContent.getBodyCode("HTML") && content.isForwardForm){

            pageX.cache.isFormForward = true;
            contentConfig.bodyType = "20-Forward";
            contentConfig.content = content["moduleId"];
            contentConfig.ext = {

                    isNew : false,
                    viewState : summaryBO._viewState,
                    "openFrom" : pageX.winParams["openFrom"],
                    templateId : summaryBO.summary.templateId,


                    rightId : content["formRightId"],
                    allowQRScan : false,
                    "indexParam" : "0",
                    "contentDataId" : content["contentDataId"],
                    "affairId" : summaryBO.summary.affairId,
                    "isLightForm" : false,
                }
        }else if(bodyType == SeeyonContent.getBodyCode("FORM")){

             contentConfig.content = content["moduleId"];
             contentConfig.ext = {
                 "isLightForm" : pageX.cache.isLightForm,
                 rightId : content["formRightId"],
                 viewState : summaryBO._viewState,
                 allowQRScan : summaryBO.summary.canScanCode =="1" ?  true :false ,
                 //原样表单参数
                 "openFrom" : pageX.winParams["openFrom"],
                 "isNew" : false,
                 "templateId" : summaryBO.summary.templateId,
                 "indexParam" : pageX.cache.formIndex || "0",
                 "contentDataId" : content["contentDataId"],
                 "affairId" : summaryBO.summary.affairId
             }


             var tsBtn = _$("#handler_switch_btn"),
                 __moduleId = content["moduleId"],
                 __right = content["formRightId"];

             tsBtn.classList.remove("display_none");

             //引导
             //新建引导 获取本地缓存, 微信端保存不了localstorage，改用DB
             cmp.storageDB.get("m3_v5_collaboration_summary_src_form_flag", function(val) {
                var isHit = val.data;
                if (!isHit || isHit != "true") {
                    var hitEle, hitType;
                    hitEle = _$("#src_form_view_hint");
                    hitType = pageX.cache.isLightForm ? cmp.i18n("collaboration.page.lable.srcForm") : cmp
                            .i18n("collaboration.page.lable.lightForm");
                    _$("#src_form_view_hint_txt", false, hitEle).innerHTML = cmp.i18n(
                            "collaboration.page.lable.srcFormHit", [ hitType ])
                    hitEle.classList.remove("display_none");
                    hitEle.querySelector(".btn").addEventListener("tap", function() {
                        cmp.storageDB.save("m3_v5_collaboration_summary_src_form_flag", "true", null, true);
                        hitEle.classList.add("display_none");
                    });
                }
            }, true);

             //原表单切换
             tsBtn.addEventListener("tap", function(){

            	 var _hitType = !pageX.cache.isLightForm ? cmp.i18n("collaboration.page.lable.srcForm") : cmp.i18n("collaboration.page.lable.lightForm");
            	 _$("#src_form_view_hint_txt", false, _$("#src_form_view_hint")).innerHTML = cmp.i18n("collaboration.page.lable.srcFormHit", [_hitType]);
                 //切换到表单页签
                 _switche2View(pageX.cache.formIndex, false);

                 _isContentInit = false;
                 _cacheSignet(false);//缓存签章
                 SeeyonContent.instance("newInputPosition").loadForm(pageX.cache.formIndex, {
                     isLightForm : !pageX.cache.isLightForm,
                     loadCallback : function(){
                         _isContentInit = true;
                         pageX.cache.isLightForm = !pageX.cache.isLightForm;

                         pageX.cache.viewLight["" + pageX.cache.formIndex] = pageX.cache.isLightForm;

                         initSignet();
                     }
                 });
             });

        }else{
            contentConfig.content = content["fileId"];
            contentConfig.lastModified = content["lastModified"];
        }
        //初始化正文
        SeeyonContent.init(contentConfig);
    }else{
        cmp.dialog.loading(false);
        _alert(cmp.i18n("collaboration.nodata.content"), _goBack);
    }
}


//附言按钮
function _showSenderComment(canAdd){
    var tempBtn = _$("#add_sender_comment");
    if(!canAdd){
        tempBtn.remove();
    }else{
        tempBtn.addEventListener("tap", function(e) {

            e.stopPropagation();//阻止冒泡

            var nextPageData = {
                "cache_subfix" : pageX.winParams.cache_subfix,
                "WebviewEvent" : WebEvents.M3_EVENT_SUMMARY + pageX.winParams.cache_subfix,
            };
            cmp.event.trigger("beforepageredirect",document);
            cmp.href.next(_collPath + "/html/details/addSenderComment.html"+colBuildVersion, nextPageData);
        });
        tempBtn.classList.remove("display_none");
    }
}


//刷新页面布局
function fnRefreshPage() {
  //延迟加载意见
    LazyUtil.addLoadedFn("lazy_listView", function(){
        cmp.listView("#contentView").refresh();
    });
}


//########################### 全文签批 begin ############################
function _downloadContentSignFile(aipFileId) {
    if (pageX.cache.aipFilePath) {
        _openContentSign(pageX.cache.aipFilePath);
        return;
    }
    cmp.dialog.loading(true);
    var downloadUrl = cmp.serverIp + "/seeyon/rest/attachment/file/" + aipFileId;
    //先下载(如果已下载，则不下载)
    cmp.att.download({
        url:downloadUrl,
        title: aipFileId + ".aip",
        origin: cmp.origin,
        extData : {
            fileId : aipFileId,
            lastModified : new Date(),
        },
        success:function(result){
            cmp.dialog.loading(false);
            if (!result) {
                alert(cmp.i18n("collaboration.tip.contentSign.openFailed"));
                return;
            }
            pageX.cache.aipFilePath = result["target"];
            _openContentSign(result["target"])
        },
        error:function(result){
            console.log(result);
            cmp.dialog.loading(false);
            alert(cmp.i18n("collaboration.tip.contentSign.openFailed"));
        }
    });
}

//封装插件需要的参数，打开原生全文签批
function _openContentSign(aipFilePath) {
    var userName = m3.userInfo.getCurrentMember().name;
    var param = {
        canEdit: summaryBO.summary.canEdit && _hasPermissions(summaryBO.pageConfig.nodeActions, "PDFSign") && summaryBO["summary"].isCanHandle && summaryBO.formIsLock !== true,
        aipFilePath: aipFilePath,
        aipValidateUrl: "http://www.dianju.cn:9239",
        aipValidateName: "",
        affairId: summaryBO.summary.affairId,
        affairState: summaryBO.summary.affairState,
        nodeName: summaryBO.summary.nodePolicy,
        baseUrl: cmp.serverIp,
        userName: userName,
    };

    var metadata = window.s3scope.metadata;
    var data = window.s3scope.data;
    var signDataMap = {};
    if (metadata && data) {
        Object.keys(metadata.fieldInfo || {}).forEach(function(key) {
            if (key.indexOf('field') != -1 && data.master[key]) {
                var fieldInfo = metadata.fieldInfo[key];
                var fName = fieldInfo.display;
                var fValue = '';
                var fieldData = data.master[key];
                if ('attachment' == fieldInfo.inputType) {//附件特殊处理
                    if (fieldData && fieldData.attData && fieldData.attData.length > 0) {
                        var fileNameArr = [];
                        fieldData.attData.forEach(function (val) {
                            if (val.filename) {
                                var sizeStr = cmp.att.countAttSize(val.size);
                                fileNameArr.push(val.filename + " (" + sizeStr + ")");
                            }
                        });
                        if (fileNameArr.length > 0) {
                            fValue = fileNameArr.join('\n\n');
                        }
                    }
                } else if (fieldData.extMap && fieldData.extMap.display){
                    var extMapDisplay = fieldData.extMap.display.replace(/<\/div><div>/g, "\n").replace(/<\/?.+?>/g, "").replace(/&nbsp;/ig, " ").replace(/&ensp;/ig, " ").replace(/&emsp;/ig, " ");
                    fValue = extMapDisplay;
                } else if ('edocflowdealoption' != fieldInfo.inputType) { //签批图片不显示到全文签批
                    fValue = fieldData.display;
                }
                signDataMap[fName] = fValue;
            }
        });
    }
    param.signDataStr = cmp.toJSON(signDataMap);

    //打开全文签批原生界面
    cmp.sign.open({
        data: param,
        success: function(result) {
            if (result) {
                pageX.cache.aipFilePath = result;
                uploadContentSignFile(result);
            } else {
                alert(cmp.i18n("collaboration.tip.contentSign.saveFailed"));
            }
        },
        error: function() {
            alert(cmp.i18n("collaboration.tip.contentSign.openFailed"));
        }
    });
}

//上传修改后的签批文件
function uploadContentSignFile(filePath) {
    cmp.dialog.loading();
    cmp.att.upload({
        url: cmp.serverIp + "/seeyon/rest/attachment?token=",
        fileList: [{
            filepath: filePath,
            fileId: cmp.buildUUID()
        }],
        title: "",
        success: function (result) {
            cmp.dialog.loading(false);
            var newFileId = JSON.parse(result.response).atts[0].fileUrl;
            if (newFileId) {
                pageX.cache.newAipFileId = newFileId;
                summaryBO.summary.aipFileId = newFileId;
            } else {
                pageX.cache.aipFilePath = "";
                pageX.cache.newAipFileId = "";
                alert(cmp.i18n("collaboration.tip.contentSign.saveFailed"));
            }
        },
        error: function (res) {
            cmp.dialog.loading(false);
            pageX.cache.aipFilePath = "";
            pageX.cache.newAipFileId = "";
            callback.error(res);
        }
    });
}

//是否是微信浏览器
function isWechat () {
    var ua = window.navigator.userAgent.toLowerCase()
    if (ua.indexOf('micromessenger') > -1) {
        return true
    }
    return false
}
//########################### 全文签批 end ############################

